<?php

namespace app\http\middleware;

use app\facade\Token;
use app\models\{User as Users};
use think\Db;
use app\facade\Redis;

class Auth
{
    use \traits\controller\Jump;
    public function handle($request, \Closure $next)
    {
        $url = '/' . $request->controller() . '/' . $request->action();
        $verify = config('auth.api');
        $url = strtolower($url);
        if (!in_array($url, $verify) && !$request->header('token')) {
            $this->result([], 999, language('base.tokenempty'));
        }
        $code = $request->ip();
        if ($request->header('token') && !in_array($url, $verify)) {
            $user_id = Token::get($request->header('token'));
            $user = Users::where('id', $user_id)->find();
            $code = $user_id;
            if (!$user) {
                $this->result([], 998, language('user.null'));
            }
            if ($user['status'] == 2) {
                $this->result([], 997, language('user.freeze'));
            }
            if ($request->header('token') != $user['token']) {
                $this->result([], 996, language('user.offline'));
            }
            $request->user_id = $user_id;
            $request->user = $user;
        }
        if ($request->isPost()) {
            $unique = $url . '_' . $code;
            $frtimes = Redis::get($unique);
            if ($frtimes) {
                $this->result([], 10000, language('base.frequently'));
            }
            Redis::setex($unique, 2, 3);
        }
        return $next($request);
    }
}
